<template>
  <div class="scheme-box flex-col-center-start " >
<!--    方案详情-->
    <el-drawer
        v-model="showTollgateBox"
        title="方案详情"
        :append-to-body="true"
        :size="computedSizeByIsPc"
    >

<!--      关卡信息-->
      <TollgateBox
                   editable
                   @select-tollgate="handleSelectTollgate"
                   v-loading="showSchemeDetailLoading" element-loading-text="加载方案中"
                   :scheme-id="activeScheme.id">
      </TollgateBox>
    </el-drawer>

<!--    新增方案表-->
    <el-drawer
        v-model="showSchemeForm"
        :title="(updateSchemeForm?'编辑':'新增')+'方案'"
        :append-to-body="true"
        :size="computedSizeByIsPc"
    >
      <InsertSchemeForm  @submit="showSchemeForm=false;refresh()" :form="updateSchemeForm" ></InsertSchemeForm>
    </el-drawer>

    <!--    头部菜单栏-->
    <div class="flex-col scheme-box-header">
      <el-button-group>
          <el-button :color="sysConfig.DANGER_COLOR" @click="handleClickInsertBtn" :icon="CirclePlusFilled" >添加方案</el-button>
        <el-button text :icon="Grid" @click="showTable=!showTable"></el-button>
        <el-button text :icon="Refresh" @click="refresh"></el-button>
      </el-button-group>
      <el-tabs   tab-position="top" @tab-click="handleTabChange" v-model="currSchemeTab">
        <el-tab-pane  label="全部方案" :name="SchemeTabName.ALL"></el-tab-pane>
        <el-tab-pane label="收藏方案" :name="SchemeTabName.COLLECTION"></el-tab-pane>
        <el-tab-pane label="已发布" :name="SchemeTabName.PUBLIC"></el-tab-pane>
        <el-tab-pane label="待审核" :name="SchemeTabName.AUDITING"></el-tab-pane>
      </el-tabs>

    </div>
<!--    空白展示-->
    <el-empty description="暂无方案" v-if="!schemeList || schemeList.length === 0" element-loading-text="加载方案中" v-loading="showSchemeListLoading">
    </el-empty>
<!--    方案展示-->
    <div  class="card-box flex-row"  style="flex: 9" >

      <el-space wrap size="large" alignment="normal" >
        <transition       appear
                          name="animate__animated animate__bounce"
                          enter-active-class="animate__zoomIn"
                          leave-active-class="animate__zoomOut"
                          v-for="(item,index) in schemeList"
                          >
        <SchemeManageCard @apply="handleClickApply"
                          @status="handleClickSchemeStatus"
                          @collection="handleClickCollection"
                          @delete="handleClickDeleteScheme"
                          @edit="handleClickEditScheme"
                          @detail="handleClickDetailScheme"
                          @share="handleClickShareScheme"
                          :scheme="item"  :key="index"></SchemeManageCard>
        </transition>
      </el-space>

    </div>

    <div class="margin-col-5" style="flex: 1" >
      <el-pagination
          v-model="pageConfig.pageNum"
          small
          :page-size="pageConfig.pageSize"
          background
          :pager-count="10"
          layout="prev, pager, next"
          :total="pageConfig.total"
      />
    </div>

  </div>
</template>

<script lang="ts" setup>

import {computed, defineEmits, ref} from "vue";
import {Chapter, SchemeQueryParam, SchemeStatus, Tollgate} from "@/ts/scheme";
import {CirclePlusFilled, Grid, Refresh} from "@element-plus/icons";
import {ElMessage, ElMessageBox, TabPaneName} from "element-plus";
import SchemeManageCard, {SchemeManageCardType} from "@/components/scheme/SchemeManageCard.vue";
import TollgateBox from "@/components/tollgate/TollgateBox.vue";

import InsertSchemeForm, {InsertSchemeFormType} from "@/components/form/InsertSchemeForm.vue";
import {isPC} from "@/utils/CommonUtil";
import {
  getSchemeById,
  getSchemeListPageByUser,
  getSchemeListPageForCollection,
  updateScheme
} from "@/api/scheme/SchemeApi";
import {collectScheme, notCollectScheme} from "@/api/scheme/CollectApi";
import sysConfig from "@/config/index"

let emit=defineEmits<{
  // eslint-disable-next-line no-unused-vars
  (e:"selectScheme",val:SchemeManageCardType):void
  // eslint-disable-next-line no-unused-vars
  (e:"selectTollgate",val:SchemeManageCardType,tollgate:Tollgate,chapter:Chapter):void
}>()

let pageConfig=ref({
  pageNum:1,
  pageSize:sysConfig.PAGE_SIZE,
  total:0
})

// eslint-disable-next-line no-unused-vars
enum SchemeTabName{
  // eslint-disable-next-line no-unused-vars
  ALL,
  // eslint-disable-next-line no-unused-vars
  COLLECTION,
  // eslint-disable-next-line no-unused-vars
  PUBLIC,
  // eslint-disable-next-line no-unused-vars
  AUDITING
}
// 方案标签页处理器映射
const schemeTabHandlerMap={
  [SchemeTabName.ALL]:getSchemeList,
  [SchemeTabName.PUBLIC]:getPublicSchemeList,
  [SchemeTabName.AUDITING]:getAuditingSchemeList,
  [SchemeTabName.COLLECTION]:getCollectionSchemeList
}

// 加载方案详情时调用
let showSchemeDetailLoading=ref(false)
// 加载方案时调用
let showSchemeListLoading=ref(false)
// 显示关卡盒子
let showTollgateBox=ref(false)
// 显示方案新增表
let showSchemeForm=ref(false)

// 当前选择的方案
let activeScheme=ref<SchemeManageCardType>({})



// 当前选择的方案tab类型：全部、我的收藏...
let currSchemeTab=ref(SchemeTabName.ALL)
// 当前tab需要执行的方法
let currSchemeTabFunction=ref<Function>(getSchemeList)


//需要修改的方案
let updateSchemeForm=ref<InsertSchemeFormType>({})
// 显示方案表格形式
let showTable = ref(false)
let schemeList = ref<SchemeManageCardType[]>([])

function refresh(){
  clearSchemeList()
  currSchemeTabFunction.value(pageConfig.value.pageNum)
}
refresh()


// 获取用户创建的方案分页
function getSchemeList(pageNum:number,param?:SchemeQueryParam){
  showSchemeListLoading.value=true
  getSchemeListPageByUser(pageNum,param).then(resp=>{
    // @ts-ignore
    if(resp.code === 200 && resp.data.records){
      schemeList.value=resp.data.records
      pageConfig.value.total=resp.data.total
    }
    showSchemeListLoading.value=false
  })
}
// 选择关卡
function handleSelectTollgate(tollgate:Tollgate,chapter:Chapter){
  emit("selectTollgate",activeScheme.value,tollgate,chapter)
  showTollgateBox.value=false
}
//  方案应用
function handleClickApply(scheme:SchemeManageCardType){
  if(scheme.schemeStatus === SchemeStatus.AUDITING){
    ElMessage({
      type:"warning",
      message:"方案审核中,无法使用"
    })
    return
  }
  emit("selectScheme",scheme)
}
// 方案分享
function handleClickShareScheme(scheme: SchemeManageCardType){
  console.log(scheme)
  ElMessage({
    type:"warning",
    message:"暂未开通分享功能"
  })
}
// 点击方案的详情
function handleClickDetailScheme(scheme: SchemeManageCardType) {


  // 显示关卡盒子
  showTollgateBox.value=true
  // 显示加载动画
  showSchemeDetailLoading.value=true

  // 记录当前方案
  activeScheme.value=scheme
  // 请求方案的章节列表内容

  showSchemeDetailLoading.value=false

}



// 点击切换方案状态
function handleClickSchemeStatus(schemeType:SchemeManageCardType){
  const status=schemeType.schemeStatus
  switch (status){
    case SchemeStatus.PRIVATE:
      ElMessageBox.confirm("确定发布方案?\n(发布方案后其他人可以收藏您的方案)","提示",{
        cancelButtonText:"取消",
        confirmButtonText:"确定",
        type:"warning",
        center:true
      }).then(()=>{
        updateScheme({
          ...schemeType,
          schemeStatus:SchemeStatus.PUBLIC
        }).then((resp)=>{
          if(resp.code === 200){
            ElMessage({
              type:"success",
              message:"发布成功"
            })
            // 重新请求数据
            refresh()
          }

        })

      }).catch(()=>{})
      break;
    case SchemeStatus.PUBLIC:
      ElMessageBox.confirm("确定切换方案状态为私有?","提示",{
        cancelButtonText:"取消",
        confirmButtonText:"确定",
        type:"warning",
        center:true
      }).then(()=>{
        updateScheme({
          ...schemeType,
          schemeStatus:SchemeStatus.PRIVATE
        }).then((resp)=>{
          if(resp.code === 200){
            ElMessage({
              type:"success",
              message:"切换成功"
            })
            // 重新请求数据
            refresh()
          }

        })
      }).catch(()=>{})
      break;
    case SchemeStatus.AUDITING:
      ElMessage({
        type:"error",
        message:"方案审核中..."
      })
       break;
  }

}

// 点击收藏
function handleClickCollection(schemeType:SchemeManageCardType){
  if(schemeType.collection){
    notCollectScheme(schemeType.id).then(resp=>{
      // @ts-ignore
      if(resp.code === 200){
        ElMessage({
          type:"info",
          message:"取消收藏"
        })
        refresh()
      }
    })

  }else{
    collectScheme(schemeType.id).then(resp=>{
      // @ts-ignore
      if(resp.code === 200){
        ElMessage({
          type:"success",
          message:"收藏成功"
        })
        refresh()
      }

    })

  }


}
// 新增方案
function handleClickInsertBtn(){
  updateSchemeForm.value.id=0
  showSchemeForm.value=true
}

// TODO api根据id获取scheme，不需要chapterList
function getScheme(id:number){
  getSchemeById(id).then(resp=>{
    // @ts-ignore
    if(resp.code === 200){
      updateSchemeForm.value={
        ...resp.data
      }
    }
  })

}
// 编辑方案
function handleClickEditScheme(scheme: SchemeManageCardType) {

  getScheme(scheme.id)
  showSchemeForm.value=true
}
// 删除方案
function handleClickDeleteScheme(scheme: SchemeManageCardType) {
  // 前端删除（可以替换成重新请求一次）
  schemeList.value.splice(schemeList.value.indexOf(scheme), 1)
  // 后端删除
  // deleteScheme(scheme.id)
  // 提示
  ElMessage({
    message: '删除成功',
    showClose: true,
    duration: 2000,
    type: 'success',
  })
}
// 清空当前方案列表
function clearSchemeList(){
  schemeList.value=[]
}
// 获取已发布的方案
function getPublicSchemeList(pageNum:number){

  getSchemeList(pageNum,{
    schemeStatus:SchemeStatus.PUBLIC
  })
}
// 获取正在审核中的方案
function getAuditingSchemeList(pageNum:number){

  getSchemeList(pageNum,{
    schemeStatus:SchemeStatus.AUDITING
  })
}
function getCollectionSchemeList(pageNum:number){
  getSchemeListPageForCollection(pageNum).then(resp=>{
    // @ts-ignore
    if(resp.code === 200){
      schemeList.value = resp.data.records
    }
  })
}
function handleTabChange(pane:TabPaneName){
  // @ts-ignore
  let handler=schemeTabHandlerMap[pane.paneName]
  currSchemeTabFunction.value=handler
  refresh()

}
// 通过scheme id 获取章节列表


let computedSizeByIsPc=computed(()=>{
  return isPC()?'60%':'100%'
})
</script>

<style scoped lang="less">
.scheme-box {
  height: 100%;
  .scheme-box-header{
    width: 100%;

  }
  .card-box{
    width: 100%;
    overflow-y: scroll;
  }

}

::-webkit-scrollbar{
  width: 0;
  height: 12px;
}
</style>